# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template.context import RequestContext
from django.views.generic.dates import DayArchiveView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.list import ListView
from main.forms import SearchForm, E_CreateForm
from main.models import Employee, Unit, DismissedEmployee, Profession
import datetime as _date

def home(request):
    return render_to_response('main/main.html', context_instance=RequestContext(request))

def success(request):
    return render_to_response('success.html', context_instance=RequestContext(request))

class EmployeeDetail(DetailView):
    template_name = 'employee/employee_detail.html'
    queryset = Employee.objects.all()

    def get_context_data(self, **kwargs):
        if not self.request.user.has_perm("main.can_view_empl"):
            raise PermissionDenied
        return super(EmployeeDetail, self).get_context_data(**kwargs)

class EmployeeByUnit(ListView):
    template_name = 'employee/employee_list.html'

    def get_queryset(self):
        unit_obj = get_object_or_404(Unit, pk__iexact=self.kwargs['pk'])
        return Employee.objects.filter(dismissed=False, actual_unit=unit_obj).order_by('lastname')

class UnitsList(ListView):
    template_name = 'employee/units.html'
    queryset = Unit.objects.all()

class BDayListView(DayArchiveView):

    def get_dated_items(self):
        year = _date.datetime.now().year # Для инициализации/ По факту не используется
        month = int(self.get_month())
        day = int(self.get_day())

        try:
            date = _date.date(year, month, day)
        except ValueError:
            raise Http404 # Выдаём ошибку если даты не существует
        
        date_field = self.get_date_field()
        
        lookup_kwargs = {
            '%s__day' % date_field: date.day,
            '%s__month' % date_field: date.month,
            'dismissed' : False
        }
        qs = self.get_dated_queryset(**lookup_kwargs)

        return (None, qs, {
            'day': date,
            'previous_day': self.get_previous_day(date),
            'next_day': self.get_next_day(date)
        })

class BDaysList(BDayListView):
    model = Employee
    date_field = 'birthday'
    template_name = 'employee/employee_bdays.html'
    allow_future = True
    allow_empty = True

class BDayTodayList(BDaysList):
    year = _date.datetime.now().year # Для инициализации
    month = _date.datetime.now().month
    day = _date.datetime.now().day

    def get_dated_items(self):
        self.day = _date.datetime.now().day
        return super(BDayTodayList, self).get_dated_items()

class DismissEmployee(ListView):
    template_name = 'employee/dismissed.html'
    queryset = DismissedEmployee.objects.all().order_by('employee__lastname')

    def get_context_data(self, **kwargs):
        if not self.request.user.has_perm("main.can_view_dis_e"):
            raise PermissionDenied
        return super(DismissEmployee, self).get_context_data(**kwargs)

class ORepairEmployee(ListView):
    template_name = 'employee/employee_orepair.html'
    queryset = Employee.objects.filter(operative_repair=True).order_by('lastname')

    def get_context_data(self, **kwargs):
        if not self.request.user.has_perm("main.can_view_orep"):
            raise PermissionDenied
        return super(ORepairEmployee, self).get_context_data(**kwargs)


def search(request):
    form = SearchForm(request.POST or None)
    qs=None
    if form.is_valid():
        qs = Employee.objects.filter(name__startswith=form.cleaned_data['name'].upper(), lastname__startswith=form.cleaned_data['lastname'].upper(), \
                                     patronymic__startswith=form.cleaned_data['patronymic'].upper()).order_by('lastname')
        if not form.cleaned_data['in_dismissed']:
            qs = qs.filter(dismissed=False)
        if form.cleaned_data['unit']:
            qs = qs.filter(actual_unit=form.cleaned_data['unit'])
        if form.cleaned_data['in_repair']:
            qs = qs.filter(operative_repair=True)

    return render_to_response('employee/search.html', {'qs':qs, 'form':form}, context_instance=RequestContext(request))

class EmployeeCreateView(CreateView):
    template_name = 'employee/employee_create.html'
    success_url = '/success/'
    form_class = E_CreateForm

    def get(self, request, *args, **kwargs):
        if request.user.has_perm('employee.add_employee') or request.user.is_superuser:
            return super(EmployeeCreateView, self).get(request, *args, **kwargs)
        else:
            raise PermissionDenied

class EmployeeUpdateView(UpdateView):
    form_class = E_CreateForm
    template_name = 'employee/employee_update.html'
    success_url = '/success/'
    queryset = Employee.objects.filter(dismissed=False)

    def get(self, request, *args, **kwargs):
        if request.user.has_perm('remployee.add_employee') or request.user.is_superuser:
            return super(EmployeeUpdateView, self).get(request, *args, **kwargs)
        else:
            raise PermissionDenied


class EmployeeDeleteView(DeleteView):
    success_url = '/success/'
    queryset = Employee.objects.filter(dismissed=False)

    def get(self, request, *args, **kwargs):
        if request.user.has_perm('employee.add_employee') or request.user.is_superuser:
            return super(EmployeeDeleteView, self).get(request, *args, **kwargs)
        else:
            raise PermissionDenied
